<template>
  <div class="app-market-dialog">
    <el-dialog title="授权到组织"
               :visible.sync="VisibleDialog"
               :close-on-click-modal="false"
               @close="dialogClose">
      <el-row :gutter="20">
        <el-form :model="requestParam"
                 size="medium">
          <el-col :span="24"
                  class="condition-style-box">
            <el-col :span="10">
              <el-form-item label-width="0px">
                <el-select v-model="requestParam.type_id"
                           @change="onTypeChange(requestParam.type_id)"
                           class="sel-style"
                           placeholder="请选择">
                  <el-option v-for="item in typeArr"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label-width="0px">
                <div class="condition-style">
                  <el-input v-model="requestParam.search"
                            v-if="requestParam.type_id=='2'"
                            placeholder="请输入项目名称"></el-input>
                  <!-- <el-input v-model="requestParam.company_name"
                            type="textarea"
                            :rows="1"
                           
                            :disabled="true"></el-input> -->
                  <div v-else
                       :title="requestParam.company_name"
                       class='content-style'>{{requestParam.company_name}}</div>
                  <el-button type="primary"
                             size="medium"
                             class="search-style"
                             v-if="requestParam.type_id=='2'"
                             @click="onSearch">查询</el-button>

                  <el-button type="primary"
                             size="medium"
                             class="sel-company-button"
                             v-if="requestParam.type_id=='3'"
                             @click="onSelUnit">选择单位</el-button>
                  <el-button @click="onReset"
                             class="sel-company-button"
                             size="medium">重置</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-col>

          <el-col :span="24"
                  v-show="requestParam.type_id=='2'">
            <!-- selection-change  
                      @select-all="handleSelectionChange"
                      @select="handleSelectionChange"
                      -->
            <el-table :data="tableData"
                      height="500px"
                      ref="tableRef"
                      @selection-change="handleSelectionChange"
                      :row-key="getUniqueIndex"
                      :header-cell-style="{background:'#f5f5f5'}">
              <el-table-column type="selection"
                               :reserve-selection="true">
              </el-table-column>
              <el-table-column width="60"
                               label="序号"
                               align="center"
                               show-overflow-tooltip>
                <template slot-scope="scope">
                  {{scope.$index+1}}
                </template>
              </el-table-column>

              <el-table-column prop="project_no"
                               label="项目编号"
                               align="center"
                               show-overflow-tooltip></el-table-column>
              <el-table-column prop="project_name"
                               label="项目名称"
                               align="center"
                               show-overflow-tooltip>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="24"
                  v-if="requestParam.type_id=='2'">
            <el-pagination @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="requestParam.page"
                           :page-sizes="[10,20,30,50,100]"
                           :page-size="requestParam.page_size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="total">
            </el-pagination>
          </el-col>
          <el-col :span="24"
                  class="bottom-box">
            <el-button size="medium"
                       @click="onCancel"> 取消</el-button>
            <el-button :type="multipleArr.length==0?'info':'primary'"
                       :disabled="multipleArr.length==0?true:false"
                       @click="onSure"
                       v-if="requestParam.type_id=='2'"
                       size="medium">确定</el-button>
            <el-button :type="compIds.length==0?'info':'primary'"
                       :disabled="compIds.length==0?true:false"
                       @click="onSure"
                       v-else
                       size="medium">确定</el-button>
          </el-col>
        </el-form>
      </el-row>
      <ChooseOrg :modal='false'
                 :dialogVisible.sync="chooseOrgDialogVisible"
                 :orgType="chooseOrgType"
                 :title="title"
                 :showAll.sync="showAllC"
                 @callback="chooseOrgCb"
                 :checkedKeysArr.sync="defaultCheckKyes"></ChooseOrg>

    </el-dialog>
  </div>
</template>
<script>

import ChooseOrg from '@/components/ChooseOrg/ChooseOrg';
import { ApplicationMarketManageApi } from '@/services/ResourceCentre'
import { MyCompanyApi } from '@/services/WorkBench';
import { ProjectListApi } from "@/services/ProjectCenter";
// import { compile } from 'vue/types/umd';

export default {
  data () {
    return {
      defaultCheckKyes: [],//树形回显
      showAllC: 0,//1：显示全部的单位
      chooseOrgType: 'company',//company
      title: '选择单位',
      chooseOrgDialogVisible: false,//弹框
      tableData: [],
      VisibleDialog: false,
      typeArr: [{//类型
        label: '单位',
        value: '3'
      }, {
        label: '项目',
        value: '2'
      }],
      dataArr: [],
      treeDataChild: [],//树
      total: 0,
      compIds: [],//多个单位id
      multipleArr: [],
      comp_id: '',//单位主键值
      requestParam: {
        company_name: '',//单位名称
        type_id: '2',
        search: "",
        created_start: "",
        created_end: "",
        province_no: "",
        city_no: "",
        area_no: "",
        major_type: "",
        status: "",
        page: 1,
        page_size: 10,
        dateRange: ""
      },
    }
  },
  components: {//注册组件
    ChooseOrg,//单位组件
  },
  props: {
    dialogTableVisible: Boolean,
    sid: String,
    callBackFunc: Function
  },

  watch: {
    dialogTableVisible (n, o) {
      this.VisibleDialog = n;
      if (n == true) {
        this.comp_id = this.$store.state.switchCompId;//单位主键值
        this.getProjectList();//项目列表   
        this.getOrgCompany();//单位列表  
        if (this.tableData.length > 0) {
          this.$nextTick(() => {
            this.$refs.tableRef.toggleRowSelection(this.tableData[0], true);
            // this.handleSelectionChange([this.tableData[0]], this.tableData[0])
          })
        }
      }
    },
    showAllC (n, o) {
    }
  },
  methods: {
    //递归遍历实现
    getStr (list) {
      if (list.length !== 0) {
        list.forEach(item => {
          let obj = {};
          obj.id = item.id;
          obj.name = item.name;
          if (item.children_list && item.children_list.length >= 0) {
            obj.children_list = this.getStr(item.children_list);
          }
          this.dataArr.push(obj)
        });
      }
      return this.dataArr;
    },
    //获取单位
    getOrgCompany () {
      let urlCompId = this.$route.query.company_id;
      let compId = this.$store.state.switchCompId;
      let objParam = {
        company_id: urlCompId ? urlCompId : compId,//单位默认当前的单位
        company_name: '',//单位名称
        show_all: 1//显示全部
      };
      return ApplicationMarketManageApi.getCompanyTree({
        params: objParam
      }).then(async (res) => {
        if (res.code == 0) {
          this.compIds = [res.data[0].id];
          this.requestParam.company_name = res.data[0].name;
          // this.dataArr = [];//主键值
          // await this.getStr(res.data);
          // this.treeDataChild = res.data;//所有单位及子单位
          console.log('c-treeDataChild=', this.treeDataChild, 'dataArr=', this.dataArr)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    onReset () {//重置
      if (this.requestParam.type_id == 3) {//单位
        this.compIds = [];
        this.defaultCheckKyes = [];
        this.requestParam.company_name = '';//重置
        this.getOrgCompany();//单位
      } else if (this.requestParam.type_id == 2) {//项目
        this.requestParam.search = '';
        this.handleSizeChange(10);
      }
    },
    getUniqueIndex (row) {//唯一的主键值
      return row.project_id;//主键值
    },
    //子组件返回的值
    chooseOrgCb (data, nameArr) {
      let compNames = [];
      this.compIds = [];
      this.compIds = data;
      if (nameArr) {
        if (nameArr.length > 0) {
          nameArr.forEach(ele => {
            compNames.push(ele.name)
          })
        }
      };
      this.defaultCheckKyes = data;
      this.requestParam.company_name = compNames.join(',');
    },
    // 获取项目列表
    getProjectList () {
      let compId = this.$store.state.switchCompId;
      let urlCompId = this.$route.query.company_id;
      let objV = {
        project_name: this.requestParam.search,
        page: this.requestParam.page,
        is_page: 1,
        page_size: this.requestParam.page_size,
        company_id: urlCompId ? urlCompId : compId
      }
      return ProjectListApi.getCompanyAllPro({
        params: {
          ...objV
        }
      }).then(
        res => {
          if (res.data) {
            this.tableData = res.data.list;
            this.total = res.data.total_count;
            // console.log('项目列表res=', res)
          }
        },
        err => {
          console.log(err);
        }
      );
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.tableRef.toggleRowSelection(row, true);
        });
      }
    },
    onTypeChange (val) {//类型切换     
    },
    //选中多行
    handleSelectionChange (selection, row) {
      this.multipleArr = [];
      this.multipleArr = selection;
      // console.log('selection=', selection, 'multipleArr=', this.multipleArr)
    },
    getIds () {//获取单位或项目的主键值
      let idsArr = [];
      if (this.requestParam.type_id == '2') {//项目
        if (this.multipleArr.length > 0) {
          this.multipleArr.forEach(ele => {
            if (idsArr.indexOf(ele.project_id) == -1) {//不存在
              idsArr.push(ele.project_id)
            }
          });
        };
      } else {//单位
      }
      return idsArr.join(',')
    },
    onSure () {//确定
      let objParams = {
        sid: this.sid,
        type: this.requestParam.type_id,
        ids: this.requestParam.type_id == '2' ? this.getIds() : this.compIds.join(',')
      }
      ApplicationMarketManageApi.applyAuth({
        data: {
          ...objParams
        }
      }).then((res) => {
        if (res.code == 0) {
          this.$refs.tableRef.clearSelection();//取消所有选中的状态
          this.callBackFunc('save')
          this.commonReset();//通用函数
          this.$message.success('授权申请提交成功')
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    onCancel () {//取消
      this.$refs.tableRef.clearSelection();//取消所有选中的状态
      if (this.requestParam.type_id == '2') {
        this.$refs.tableRef.clearSelection()
      }
      this.multipleArr = [];
      this.callBackFunc('cancel');
      this.commonReset();//通用函数
    },
    handleSizeChange (val) {
      this.requestParam.page_size = val;
      this.handleCurrentChange(1);//刷新
    },
    handleCurrentChange (val) {
      this.requestParam.page = val;
      this.getProjectList();//刷新
    },
    onSelUnit () {//选择单位
      this.showAllC = 1;//显示所有的单位
      this.defaultCheckKyes = this.compIds;
      this.chooseOrgDialogVisible = true;//选择单位的弹框
    },
    onSearch () {//查询
      this.handleCurrentChange(1);//刷新
    },
    commonReset () {
      this.compIds = [];
      this.requestParam = this.$options.data().requestParam;
      this.multipleArr = [];
      this.VisibleDialog = false;
      this.$emit('update:sid', '');
      this.$emit('update:dialogTableVisible', false);
    },

    dialogClose () {//弹框关闭
      this.$refs.tableRef.clearSelection();//取消所有选中的状态
      this.commonReset();//通用函数
    }
  },
  async created () {
    this.comp_id = this.$store.state.switchCompId;//单位主键值
    this.VisibleDialog = this.dialogTableVisible;
    await this.getProjectList();//项目列表
    await this.getOrgCompany();//获取单位
    if (this.tableData.length > 0) {
      this.$nextTick(() => {
        // this.$refs.tableRef.toggleRowSelection(this.tableData[0], true);
        // this.handleSelectionChange([this.tableData[0]], this.tableData[0])
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.app-market-dialog {
  .content-style {
    text-overflow: ellipsis; //表示当文本溢出时是否显示省略标记，ellipsis表示省略号效果，clip 表示截取的效果。
    overflow: hidden; //将文本溢出的内容隐藏。
    white-space: nowrap; // 是禁止文字换行。
    width: 100%;
  }
  .condition-style-box {
    padding: 0px !important;
    .search-style {
      margin-left: 14px;
    }
    .condition-style {
      display: flex;
      flex-direction: row;
      .sel-company-button {
        height: 36px !important;
        margin-left: 14px;
      }
    }
  }
}

.bottom-box {
  display: flex;

  flex-direction: row;

  justify-content: flex-end;

  margin-top: 20px;
}

.sel-style {
  width: 100% !important;
}
</style>